import { t } from 'i18next'
import type { Dayjs } from 'dayjs'
import dayjs from '@/plugins/dayjs'
import { useMemo, useEffect } from 'react'
import { MeetingInfo } from '@/api/myMeeting/interface'
import { StyledCalendar, StyledColumn } from './style'
import { percentOfDay, transMeetingList, TIME, weekList } from './translate'
import ColumnBackground from './components/ColumnBackground'
export interface CalendarProps {
	systemDate: string
	meetingList: MeetingInfo[]
	startTime: Dayjs
}
type ColumnLeftProps = {
	currentTime: Dayjs
}
function currentWeekData(dayjsDate: Dayjs): Dayjs[] {
	const currenWeekStartDay = dayjsDate.startOf('week')
	return new Array(7).fill('').map((_, index) => currenWeekStartDay.add(index, 'day'))
}
const Calendar = ({ systemDate, meetingList, startTime }: CalendarProps) => {
	const currentTime = useMemo(() => dayjs(systemDate), [systemDate])
	const meetings = useMemo(() => transMeetingList(meetingList), [meetingList])
	const weekData = useMemo(() => currentWeekData(startTime), [startTime])
	const ColumnLeft = ({ currentTime }: ColumnLeftProps) => {
		return (
			<StyledColumn w={70} className="list-title">
				{TIME.map((t, index) => {
					return (
						<div className="cell" key={t}>
							<p className="times">{t}</p>
						</div>
					)
				})}
				{currentTime.startOf('week').isSame(startTime, 'date') && (
					<div className="current-time-triangle" style={{ top: percentOfDay(currentTime) }}></div>
				)}
			</StyledColumn>
		)
	}
	useEffect(() => {
		let dom = document.querySelector('.calendar-body')
		if (!dom) return
		if (!document.body.scrollTo) {
			dom.scrollTop = (currentTime.hour() - 2) * 100
		} else {
			dom.scrollTo({
				top: (currentTime.hour() - 2) * 100,
				behavior: 'smooth',
			})
		}
	}, [currentTime])
	return (
		<StyledCalendar className="calendar-panel">
			<div className="calendar-header">
				{weekData.map((w, index) => (
					<div key={index} className="header-item">
						{w.format('MM/DD') + t('(星期{{num}})', { num: weekList[w.day()] })}
					</div>
				))}
			</div>
			<div className="calendar-body" draggable={false}>
				<div className="calendar-list">
					<ColumnLeft currentTime={currentTime}></ColumnLeft>
					{weekData.map((x) => {
						return (
							<ColumnBackground
								key={x.format('YYYY-MM-DD')}
								day={x.format('YYYY-MM-DD')}
								cellDivide={4}
								currentTime={currentTime}
								meetingList={meetings.filter((y) => y.day.isSame(x, 'day'))}
							></ColumnBackground>
						)
					})}
				</div>
			</div>
			<div className="card-modal"></div>
		</StyledCalendar>
	)
}
export default Calendar
